package com.hyfd.task;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.hyfd.common.utils.GetUtil;
import com.hyfd.common.utils.MD5;
import com.hyfd.common.utils.ToolHttp;
import com.hyfd.common.utils.XmlUtils;
import com.hyfd.common.utils.YiGuangAES;
import com.hyfd.dao.mp.OrderDao;
import com.hyfd.dao.mp.ProviderPhysicalChannelDao;
import com.hyfd.rabbitMq.RabbitMqProducer;
import com.hyfd.rabbitMq.SerializeUtil;

@Component
public class YiGuangFlowTask {

	@Autowired
	ProviderPhysicalChannelDao providerPhysicalChannelDao;//物理通道信息
	@Autowired
	OrderDao orderDao;//订单
	@Autowired
	RabbitMqProducer mqProducer;//消息队列生产者
	private static Logger log = Logger.getLogger(BoLuoMiNewFlowTask.class);
	
//	@Scheduled(fixedDelay = 60000)
	public void queryBoLuoMiNewOrder(){
		Map<String,Object> map = new HashMap<String,Object>();

		int flag = -1;
		try{
			String id = "0000000103";
			Map<String,Object> channel = providerPhysicalChannelDao.selectByPrimaryKey(id);//获取通道的数据
			String defaultParameter = (String) channel.get("default_parameter");//默认参数
			Map<String,String> paramMap = XmlUtils.readXmlToMap(defaultParameter);
			String queryOrderUrl = paramMap.get("queryOrderUrl");
			String api_userid = paramMap.get("api_userid");// 身份ID
            String securitKey = paramMap.get("securitKey");// 加密key
			Map<String,Object> param = new HashMap<String,Object>();
			param.put("dispatcherProviderId", id);
			param.put("status", "1");
			List<Map<String,Object>> orderList = orderDao.selectByTask(param);
			for(Map<String,Object> order : orderList){
				String orderId = order.get("orderId")+"";
				map.put("orderId", orderId);
				String mobile = order.get("phone")+"";
//	            // 组装包体
//	            JSONObject jsonBody = new JSONObject();
//	            jsonBody.put("api_userid", api_userid);
//	            jsonBody.put("order_no", orderId);
//	            jsonBody.put("mobile", mobile);
//	            
//	            String data = YiGuangAES.encrypt(jsonBody.toString(), securitKey);
//	            JSONObject json = new JSONObject();
//	            json.put("api_userid", api_userid);
//	            json.put("api_data", data);
	            
//	            String contentType = "application/x-www-form-urlencoded";
	            // post请求
	            String result = byOrder(api_userid, securitKey, orderId, mobile, queryOrderUrl);//ToolHttp.post(false, queryOrderUrl, json.toString(), contentType);
				if(null!=result&&!"".equals(result)){
					JSONObject jObject = JSONObject.parseObject(result);
	                String resultCode = jObject.getString("retcode");
	                String resultMsg = jObject.getString("retmsg");
	               
                	map.put("resultCode", resultCode + ":" + resultMsg);
                	if("2".equals(resultCode)){
                		continue;
                	}else if("1".equals(resultCode)){
                		flag=1;
                	}else if("0".equals(resultCode)){
                		flag=0;
                	}
				
				map.put("status", flag);
				mqProducer.sendDataToQueue(RabbitMqProducer.Result_QueueKey, SerializeUtil.getStrFromObj(map));
				}
			}
		}catch(Exception e){
			log.error("易广流量查询Task出错"+e);
		}
	}
	public String sendPost(String urls,String param){
        StringBuffer sb=new StringBuffer();
        try{
            URL url = new URL(urls);
            URLConnection connection = url.openConnection();
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.connect();
            OutputStreamWriter outer = new OutputStreamWriter(connection.getOutputStream(),"UTF-8");
            outer.write(param);
            outer.flush();
            outer.close();
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            String inlin="";            
            while ((inlin = in.readLine()) != null) {
                sb.append(inlin);
            }
            in.close();            
        }catch(Exception e){
            e.printStackTrace();
        }
        return sb.toString();
    }
    public String byOrder(String userid,String key,String orderNo, String mobile,String apiUrl) {
        String rets = "";
        StringBuffer sbf = new StringBuffer();
        sbf.append("{");
        sbf.append("\"api_userid\":\"").append(userid).append("\",");
//        sbf.append("\"product_id\":\"").append(product).append("\",");
        sbf.append("\"mobile\":\"").append(mobile).append("\",");
        sbf.append("\"order_no\":\"").append(orderNo).append("\"");
        sbf.append("}");
        String jsonstr = sbf.toString();
        jsonstr = YiGuangAES.encrypt(jsonstr, key);    
        String param = (new StringBuilder()).append("api_userid=").append(userid).append("&api_data=").append(jsonstr).toString();    
        rets = sendPost(apiUrl, param);
        return rets;
      }
	
}
